package com.hundsun.yr.universal.p2p.db;

import java.util.ArrayList;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.text.TextUtils;
import android.util.Log;

import com.hundsun.yr.universal.p2p.bean.CityBean;
import com.hundsun.yr.universal.p2p.bean.ProvinceBean;

/**
 * @Title: AreaDB.java
 * @Description: 地区查询类
 * @date 2016-2-1 上午9:29:29
 * @author:hejun.shen
 * @email:shenhj15971@hundsun.com
 * @replace author:
 * @replace date:
 * @version V1.0
 */
public class AreaDB {

	private AreaDBManager dbHelper;
	private SQLiteDatabase db;
	private ArrayList<ProvinceBean> options1Items = new ArrayList<ProvinceBean>();
	private ArrayList<ArrayList<CityBean>> options2Items = new ArrayList<ArrayList<CityBean>>();

	public AreaDB(Context context) {
		db = context.openOrCreateDatabase(AreaDBManager.DB_NAME, Context.MODE_PRIVATE, null);
		dbHelper = new AreaDBManager(context);
		dbHelper.openDatabase();
		Log.i("FileTest", "************************open db*****************************");
		searchAddressList();
	}

	/**
	 * 查询地址库
	 */
	private void searchAddressList() {
		db = SQLiteDatabase.openOrCreateDatabase(AreaDBManager.DB_PATH + "/" + AreaDBManager.DB_NAME, null);
		String sql = "select c.name,p.name,c.code,p.code from province p,city c where c.provincecode=p.code";
		Cursor c = db.rawQuery(sql, null);
		c.moveToFirst();
		String province = null;
		ArrayList<CityBean> citylist = new ArrayList<CityBean>();
		do{
			String temp = province;
			province = c.getString(1);
			if (!TextUtils.equals(province, temp)) {
				ProvinceBean provinceBean = new ProvinceBean();
				provinceBean.setName(province);
				provinceBean.setCode(c.getString(3));//获取并设置province code
				options1Items.add(provinceBean);
				if (temp != null) {
					options2Items.add(citylist);
					citylist = new ArrayList<CityBean>();
				}
			}
//			String city = c.getString(0);
			CityBean cityBean = new CityBean();
			cityBean.setCode(c.getString(2));
			cityBean.setName(c.getString(0));
			citylist.add(cityBean);
		}while(c.moveToNext());
		options2Items.add(citylist);
	}
	/**
	 * 获取所有城市列表
	 * @return
	 */
	public ArrayList<ArrayList<CityBean>> getCitys(){
		return options2Items;
	}
	
	/**
	 * 获取所有省份列表
	 * @return
	 */
	public ArrayList<ProvinceBean> getProvinces(){
		return options1Items;
	}

	/**
	 * 关闭数据库
	 * 
	 */
	public void closeDB() {
		dbHelper.closeDatabase();
	}

}
